package com.ttbj.core.jpush;

import java.net.URI;
import java.net.URISyntaxException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.ttbj.core.bean.JpushModel;
import com.ttbj.core.jpush.config.JpushConfig;
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import io.netty.handler.codec.http.HttpMethod;

/**
 * Jpush
 * 
 * @author Administrator
 *
 */

public class Jpush {
	public final static Logger LOGGER = LoggerFactory.getLogger(Jpush.class);
	public static void push(JpushModel jpushModel) {
		ClientConfig clientConfig = ClientConfig.getInstance(); // 获取极光的客户端配置信息
		String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME); // 配置推送的主机地址样式
		final NettyHttpClient client = new NettyHttpClient(
				ServiceHelper.getBasicAuthorization(JpushConfig.APP_KEY, JpushConfig.MASTERSECRET), null, clientConfig);
		try {
			URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
			PushPayload payload = buildPushController(jpushModel);
			LOGGER.info("send content: "+payload.toString());
			client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
				@Override
				public void onSucceed(ResponseWrapper wrapper) {
					/*处理回调*/
					LOGGER.info("Got result: " + wrapper.responseContent);
				}
			});
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}

	private static PushPayload buildPushController(JpushModel jpushModel) {
		String registId = jpushModel.getRegistId();
		PushPayload pushPayload = null;
		if (StringUtils.isEmpty(registId)) { // 发送全部
			pushPayload =buildPushMessageMass(jpushModel);
		} else { // 发送单个
			pushPayload = buildPushMessageSingle(jpushModel); 
		}
		return pushPayload;
	}

	private static PushPayload buildPushMessageSingle(JpushModel jpushModel) { // 发送给单个用户单条信息的PushPayload
		return PushPayload.newBuilder().setPlatform(Platform.android())
				.setAudience(Audience.registrationId(jpushModel.getRegistId())).setMessage(Message.newBuilder()
						.setMsgContent(jpushModel.getContentChain()).addExtra("from", "JPush").build())
				.build();
	}

	private static PushPayload buildPushMessageMass(JpushModel jpushModel) { // 发送全部的设备的信息
		return PushPayload.newBuilder().setPlatform(Platform.android())
				.setAudience(Audience.all()).setMessage(Message.newBuilder()
						.setMsgContent(jpushModel.getContentChain()).addExtra("from", "JPush").build())
				.build();
	}

}
